<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="12" :md="15" :lg="15" :xl="15" style="margin-bottom: 10px">
        <el-card class="box-card">
          <!--工具栏-->
          <div class="head-container">
            <div>
              <!-- 搜索 -->
              <el-input
                v-model="query.blurry"
                clearable
                size="small"
                placeholder="输入名称或者描述搜索"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="toQuery"
              />
              <span><el-button
                class="filter-item"
                size="mini"
                type="success"
                icon="el-icon-search"
                @click="toQuery"
              >搜索</el-button></span>
            </div>
            <div class="crud-opts">
              <span class="crud-opts-left">
                <el-button
                  class="filter-item"
                  size="mini"
                  type="primary"
                  icon="el-icon-plus"
                  @click="toAdd"
                >
                  新增
                </el-button>
                <el-button
                  slot="reference"
                  class="filter-item"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  :loading="delAllLoading"
                  @click="toDelete"
                >
                  删除
                </el-button>
              </span>
            </div>
          </div>
          <!--表格渲染-->
          <el-table
            ref="table"
            v-loading="loading"
            :data="dataList"
            highlight-current-row
            style="width: 100%;"
            @selection-change="selectionChangeHandler"
            @current-change="handleCurrentChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column :show-overflow-tooltip="true" prop="name" label="名称" />
            <el-table-column :show-overflow-tooltip="true" prop="pcIcon" label="PC端图标">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.pcIcon"
                  slot="prefix"
                  :src="(baseUrl.substring(0,baseUrl.length-1))+scope.row.pcIcon"
                  style="height: 32px;width: 32px;"
                />
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="appIcon" label="移动端图标">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.appIcon"
                  slot="prefix"
                  :src="(baseUrl.substring(0,baseUrl.length-1))+scope.row.appIcon"
                  style="height: 32px;width: 32px;"
                />
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="sfqy">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.sfqy"
                  active-color="#409EFF"
                  inactive-color="#F56C6C"
                  @change="changeEnabled(scope.row, scope.row.sfqy)"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-permission="['admin','service:edit','service:del']"
              label="操作"
              width="180px"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="toEdit(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" icon="el-icon-s-tools" @click="toSet(scope.row)">设置</el-button>
                <el-button type="text" icon="el-icon-delete" size="mini" @click="toDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="query.page"
            :page-size="query.size"
            :total="pagerSize"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @current-change="pagerHandleCurrentChange"
            @size-change="pagerHandleSizeChange"
          />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="9" :lg="9" :xl="9">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-alert
              :title="(undefined=== service||service.name === undefined) ? '当前选中服务：':'当前选中服务：'+ service.name"
              type="warning"
              :closable="false"
              show-icon
            />
          </div>
          <el-button
            class="filter-item"
            size="mini"
            style="float: right;padding: 4px 10px"
            type="primary"
            icon="el-icon-plus"
            @click="toRoleAdd()"
          >新增
          </el-button>
          <div class="head-container">
            <el-input
              v-model="queryRole.label"
              clearable
              size="small"
              placeholder="输入字典标签查询"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="toQuery"
            />
            <span><el-button
              class="filter-item"
              size="mini"
              type="success"
              icon="el-icon-search"
              @click="toRoleQuery"
            >搜索</el-button></span>
          </div>
          <el-table
            ref="table"
            v-loading="roleLoading"
            :data="roleDataList"
            highlight-current-row
            style="width: 100%;"
            @selection-change="roleSelectionChangeHandler"
          >
            <el-table-column label="角色名称" prop="role.name" />
            <el-table-column label="操作" width="130px" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="toDeleteRole(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="queryRole.page"
            :page-size="queryRole.size"
            :total="rolePageSize"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @current-change="pagerHandleCurrentChange"
            @size-change="pagerHandleSizeChange"
          />
        </el-card>
      </el-col>
    </el-row>
    <service-entity ref="service" @fetch-data="fetchData" />
    <service-role ref="role" @fetch-data-role="fetchDataRole" />
    <service-set ref="set" @fetch-data="dataSet" />
  </div>
</template>
<script>
import { queryAllByPager, edit, del } from '@/api/system/serviceManager';
import ServiceEntity from '@/views/system/service/entity';
import ServiceRole from '@/views/system/service/role';
import ServiceSet from './edit';
import { queryAllRoleByService, del as roleDel } from '@/api/system/roleService';
export default {
  name: 'ManagerServiceIndex',
  // 数据字典
  dicts: ['user_status'],
  components: { ServiceEntity, ServiceRole, ServiceSet },
  data() {
    return {
      delAllLoading: false,
      loading: false,
      roleLoading: false,
      roleDataList: [],
      dataList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      serviceId: [],
      pagerSize: 10,
      rolePageSize: 10,
      service: {},
      query: {
        blurry: '',
        page: 1,
        size: 10
      },
      queryRole: {
        label: '',
        page: 1,
        size: 10,
        serviceId: null
      }
    };
  },
  created() {
    this.initData();
  },
  methods: {
    toQuery() {
      this.query.page = 1;
      this.initData();
    },
    toRoleQuery() {
      this.queryRole.page = 1;
      this.initRoleDate();
    },
    toAdd() {
      this.$refs.service.openEntity();
    },
    toRoleAdd() {
      if (undefined !== this.service && undefined !== this.service.id) {
        this.$refs.role.openEntity(this.service);
      } else {
        this.$message.error('请选择服务');
      }
    },
    toEdit(data) {
      if (undefined !== data.jxx && data.jxx !== null && data.jxx !== '') {
        data.dataList = JSON.parse(data.jxx);
      } else {
        data.dataList = [];
      }
      this.$refs.service.openEntity(data);
    },
    toSet(data) {
      this.$refs.set.openEntity(data);
    },
    initRoleDate() {
      queryAllRoleByService(this.queryRole).then(res => {
        const { content, totalElements } = res;
        this.rolePageSize = totalElements;
        this.roleDataList = content;
      }).catch(() => {
        console.log('初始化角色信息失败！');
      });
    },
    initData() {
      queryAllByPager(this.query).then(res => {
        const { content, totalElements } = res;
        this.pagerSize = totalElements;
        this.dataList = content;
      }).catch(() => {
        console.log('初始化服务数据失败！');
      });
    },
    toDelete(data) {
      if (data.id !== null && undefined !== data.id) { // 单个删除
        this.serviceId = [];
        this.serviceId.push(data.id);
        this.$confirm('此操作将永久删除' + data.name + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(this.serviceId).then(res => {
            this.$message.success('删除成功！');
            this.initData();
            this.serviceId = [];
          }).catch(() => {
            this.$message.error('删除失败！');
          });
        }).catch(() => {
          this.$message.success('取消删除成功！');
        });
      } else {
        if (this.serviceId === null || this.serviceId.length === 0) {
          this.$message.info('请选择删除项！');
        } else {
          this.$confirm('此操作将永久删除选中记录，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            del(this.serviceId).then(res => {
              this.$message.success('删除成功！');
              this.initData();
              this.serviceId = [];
            }).catch(() => {
              this.$message.error('删除失败！');
            });
          }).catch(() => {
            this.$message.success('取消删除成功！');
          });
        }
      }
    },
    toDeleteRole(data) {
      if (data.id !== null && undefined !== data.id) {
        const rolesId = [];
        rolesId.push(data.id);
        this.$confirm('此操作将永久删除' + data.role.name + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          roleDel(rolesId).then(res => {
            this.$message.success('删除成功！');
            this.initRoleDate();
            this.serviceId = [];
          }).catch(() => {
            this.$message.error('删除失败！');
          });
        }).catch(() => {
          this.$message.success('取消删除成功！');
        });
      } else {
        this.$message.error('请选择删除项！');
      }
    },
    selectionChangeHandler(val) {
      if (val === null || val.length === 0) {
        this.serviceId = [];
      } else {
        this.serviceId = val.map((res) => {
          return res.id;
        });
      }
    },
    roleSelectionChangeHandler(val) {
      if (val === null || val.length === 0) {
        this.roleIds = [];
      } else {
        this.roleIds = val.map((res) => {
          return res.id;
        });
      }
    },
    handleCurrentChange(val) {
      if (undefined !== val && val !== null && undefined !== val.id) {
        this.service = val;
        this.queryRole.serviceId = val.id;
        this.initRoleDate();
      }
    },
    pagerHandleCurrentChange(val) {
      this.query.page = val;
      this.initData();
    },
    pagerHandleSizeChange(val) {
      this.query.size = val;
      this.initData();
    },
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        edit(data).then(res => {
          this.$message.success('更新成功');
        }).catch(() => {
          data.enabled = !data.enabled;
        });
      }).catch(() => {
        data.enabled = !data.enabled;
      });
    },
    fetchData() {
      this.initData();
    },
    fetchDataRole() {
      this.initRoleDate();
    },
    dataSet() {}
  }
};
</script>

<style scoped>
.crud-opts {
  padding: 4px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}
.crud-opts .crud-opts-right {
  margin-left: auto;
}
</style>
